import React, { PureComponent } from 'react'
import PropTypes from 'prop-types'
import { Icon, Button, Form, Input, Dropdown, Menu, Divider, Alert } from 'antd'
import CountDown from 'ant-design-pro/lib/CountDown'
import _ from 'lodash'
import 'styles/account.scss'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { passportActions } from 'reduxs'
import { HttpServices, REDUX_FETCH_TIMEOUT, showEmail } from 'services/utils'
import { getToken } from 'services/token'
import fetchMock from 'fetch-mock'
import QueueAnim from 'rc-queue-anim'

const FormItem = Form.Item

@connect(
  state => ({
    retrievekeyPending  : state.Passport.retrievekeyPending,
    retrievekeyError    : state.Passport.retrievekeyError,
    retrievekeyMessage  : state.Passport.retrievekeyMessage,
  }),
  dispatch => ({
    actions: bindActionCreators({ ...passportActions }, dispatch)
  })
)
@Form.create()
export default class Retrievekey extends PureComponent {

  static propTypes = {
    user: PropTypes.object,
    mode: PropTypes.oneOf(['email', 'phone']),
    type: PropTypes.oneOf(['password', 'email', 'phone']),
    onPressNext: PropTypes.func
  }

  static defaultProps = {
    user: null,
    mode: 'email',
    type: 'password',
    onPressNext: () => null
  }

  constructor (props) {
    super(props)
    this.state = {
      targetTime: -1,
      modeType: props.mode,
      alert: null
    }
  }

  componentWillReceiveProps (nextProps) {
    const { retrievekeyError, retrievekeyMessage } = nextProps
    if (retrievekeyError === 0) {
      return this.props.onPressNext()
    }
    if (retrievekeyError !== this.props.retrievekeyError) {
      retrievekeyError > 0 && this.setState({ alert: (
        <Alert
          style={{ margin: '0 40px 24px 40px' }}
          message={retrievekeyMessage}
          type="error"
          showIcon
          key="aaa"
        />
      )})
    }
  }

  render () {
    const { onPressNext, form, user, retrievekeyPending } = this.props
    const { getFieldDecorator } = form
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 },
    }
    const modeCell = {
      ['email']: { name: '邮箱', fullName: '电子邮箱', value: showEmail(user.email) },
      ['phone']: { name: '手机', fullName: '手机号码', value: user.phone, disabled: true },
    }
    const cell = modeCell[this.state.modeType]
    return (
      <div style={{ marginTop: 80 }}>
        <div style={{ margin: 'auto', display: 'flex', justifyContent: 'center', flexDirection: 'column' }}>
          <span style={{ width: 600, height: 24, borderBottom: '1px #999 solid', margin: 'auto' }}>
            {cell.name}验证码验证 
            <span style={{ marginLeft: 20 }}>账户 <b>{user.username}</b> 为确认是你本人操作，请完成以下验证</span>
          </span>
          <Form
            className="account-form"
            style={{ margin: 'auto', marginTop: 40 }}
            layout="horizontal" 
            onSubmit={this.handleSubmit}
            >
            {retrievekeyPending ? null : (
              <QueueAnim component="div" type={['bottom', 'top']} leaveReverse>
                {this.state.alert ? this.state.alert : null}
              </QueueAnim>
            )}
            <FormItem
              {...formItemLayout}
              style={{ marginBottom: 2 }}
              label={cell.fullName}
              >
              {cell.value}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label="验证码"
              >
              {getFieldDecorator('code', {
                rules: [
                  { required: true, message: '请输入验证码!' },
                ],
              })(
                <Input style={{ width: 200 }} placeholder="6位数字" maxLength={6} />
              )}
              <Button 
                type="dashed" 
                style={{ width: 180, marginTop: 10, marginLeft: 10 }}
                onClick={this.handleSendCoode}
                disabled={this.state.targetTime > 0}
                >
                {this.state.targetTime > 0 ? (
                  <CountDown 
                    style={{ fontSize: 12 }} 
                    target={this.state.targetTime} 
                    format={ time => parseInt(time / 1000) + ' 秒后，可重新获取验证码' }
                    onEnd={this.handleCountDownEnd} 
                    />
                ) : (this.state.targetTime === 0 ? '重新' : '') + '获取验证码'}
              </Button>
            </FormItem>
            <FormItem
              wrapperCol={{ span: 16, offset: 6 }}
              >
              <Button 
                type="primary" 
                htmlType="submit"
                style={{ width: 150, height: 36, marginTop: 10, backgroundColor: '#188fff', borderColor: '#1890ff' }}
                //loading
                loading={retrievekeyPending}
                >
                确定
              </Button>
              <Dropdown 
                overlay={(
                  <Menu className="app-header-menu" onClick={this.handleClickMode}>
                    {_.keys(modeCell).map((item, i) => {
                      let itemInfo = modeCell[item]
                      return (
                        <Menu.Item 
                          key={item} 
                          className={`app-header-menu-span${itemInfo.disabled ? '-disabled' : ''}`}
                          disabled={itemInfo.disabled}
                          >
                          {itemInfo.name}验证码
                        </Menu.Item>
                      )
                    })}
                  </Menu>
                )}
                trigger="click"
                >
                <a className="ant-dropdown-link" style={{ marginLeft: 30 }}>
                  其它操作 <Icon type="down" />
                </a>
              </Dropdown>
            </FormItem>
          </Form>
          <Divider dashed />
          <div style={{ margin: '0 60px'}}>
            <h2 style={{ fontSize: 15, marginBottom: 16 }}>获取验证码</h2>
            <p style={{ lineHeight: 1.8, marginLeft: 20 }}>1、验证码获取间隔为 60 秒。</p>
            <p style={{ lineHeight: 1.8, marginLeft: 20 }}>2、验证码 15 分钟内输入有效，验证码等同于密码，打死也不能告诉别人。</p>
          </div>
        </div>
      </div>
    )
  }

  handleSendCoode = () => {
    setTimeout(async () => {
      try {
        const token = getToken()
        const header = {
          Authorization: token
        }
        const result = await HttpServices.GET(`/retrievekey/${this.state.modeType}/${this.props.type}`, null, header)
        fetchMock.restore()
        this.setState({ targetTime: new Date().getTime() + 60000 })
      } catch (error) {
        
      }
    }, REDUX_FETCH_TIMEOUT)
  }

  handleCountDownEnd = () => {
    this.setState({ targetTime: 0 })
  }

  handleClickMode = ({ key }) => {
    this.setState({ modeType: key })
  }

  handleSubmit = (e) => {
    e && e.preventDefault()
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.props.actions.retrievekey(values)
        //this.props.onPressNext()
      }
    })
  }
}